<template>
  <div class="distribution-dashboard">
    <!-- 页面标题和控制栏 -->
    <div class="dashboard-header">
      <div class="header-left">
        <h1 class="dashboard-title">
          <el-icon class="title-icon"><Shop /></el-icon>
          经销看板
        </h1>
        <div class="update-time">最后更新时间: {{ updateTime }}</div>
      </div>
      <div class="header-controls">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :shortcuts="dateShortcuts"
          @change="handleDateChange"
        />
        <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 实时数据指标卡片 -->
    <div class="realtime-metrics">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="metric-card online-brands">
            <div class="metric-icon">
              <el-icon><Shop /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ realtimeData.onlineBrands }}</div>
              <div class="metric-label">在线品牌数</div>
              <div class="metric-status online">实时</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="metric-card realtime-visitors">
            <div class="metric-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ formatNumber(realtimeData.realtimeVisitors) }}</div>
              <div class="metric-label">实时访客数</div>
              <div class="metric-status online">实时</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="metric-card today-amount">
            <div class="metric-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ formatCurrency(realtimeData.todayAmount) }}</div>
              <div class="metric-label">今日成交金额(万元)</div>
              <div class="metric-status positive">+12.5%</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="metric-card conversion-rate">
            <div class="metric-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="metric-content">
              <div class="metric-value">{{ formatPercentage(realtimeData.realtimeConversionRate) }}</div>
              <div class="metric-label">实时转化率</div>
              <div class="metric-status positive">+2.3%</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 概览指标 -->
    <div class="overview-section">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="overview-card total-brands">
            <div class="card-content">
              <div class="card-value">{{ overviewMetrics.totalBrands }}</div>
              <div class="card-label">总品牌数</div>
              <div class="card-growth" :class="getGrowthClass(overviewMetrics.brandGrowthRate)">
                <el-icon><Top v-if="overviewMetrics.brandGrowthRate >= 0" /><Bottom v-else /></el-icon>
                {{ formatGrowthRate(overviewMetrics.brandGrowthRate) }}
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="overview-card active-brands">
            <div class="card-content">
              <div class="card-value">{{ overviewMetrics.activeBrands }}</div>
              <div class="card-label">活跃品牌数</div>
              <div class="card-sub">活跃率: {{ formatPercentage(overviewMetrics.activeBrandRate) }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="overview-card total-amount">
            <div class="card-content">
              <div class="card-value">{{ formatCurrency(overviewMetrics.totalTransactionAmount) }}</div>
              <div class="card-label">总成交金额(万元)</div>
              <div class="card-growth" :class="getGrowthClass(overviewMetrics.amountGrowthRate)">
                <el-icon><Top v-if="overviewMetrics.amountGrowthRate >= 0" /><Bottom v-else /></el-icon>
                {{ formatGrowthRate(overviewMetrics.amountGrowthRate) }}
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="overview-card avg-value">
            <div class="card-content">
              <div class="card-value">{{ formatCurrency(overviewMetrics.avgTransactionValue) }}</div>
              <div class="card-label">平均客单价(元)</div>
              <div class="card-sub">转化率: {{ formatPercentage(overviewMetrics.overallConversionRate) }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 主要分析区域 -->
    <el-row :gutter="24" class="main-analysis">
      <!-- 趋势分析 -->
      <el-col :span="16">
        <el-card class="trend-card">
          <template #header>
            <div class="card-header">
              <span>趋势分析</span>
              <el-radio-group v-model="trendType" size="small">
                <el-radio-button value="amount">成交金额</el-radio-button>
                <el-radio-button value="brands">品牌数量</el-radio-button>
                <el-radio-button value="conversion">转化率</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" class="chart-container" style="height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 品牌排行榜 -->
      <el-col :span="8">
        <el-card class="ranking-card">
          <template #header>
            <div class="card-header">
              <span>品牌排行榜</span>
              <el-button text @click="showBrandDetail">查看详情</el-button>
            </div>
          </template>
          <div class="ranking-list">
            <div 
              v-for="(brand, index) in brandRanking" 
              :key="brand.brandName"
              class="ranking-item"
              :class="`rank-${index + 1}`"
            >
              <div class="rank-number">{{ index + 1 }}</div>
              <div class="brand-info">
                <div class="brand-name">{{ brand.brandName }}</div>
                <div class="brand-category">{{ brand.mainCategory }}</div>
              </div>
              <div class="brand-metrics">
                <div class="metric-amount">{{ formatCurrency(brand.transactionAmount) }}万</div>
                <div class="metric-trend">
                  <el-icon :class="getTrendClass(brand.trendIcon)">
                    <Top v-if="brand.trendIcon === 'up'" />
                    <Minus v-else-if="brand.trendIcon === 'stable'" />
                    <Bottom v-else />
                  </el-icon>
                  {{ formatGrowthRate(brand.growthRate) }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分布分析 -->
    <el-row :gutter="24" class="distribution-analysis">
      <!-- 类目分布 -->
      <el-col :span="12">
        <el-card class="category-card">
          <template #header>
            <div class="card-header">
              <span>类目分布</span>
              <el-select v-model="categoryLevel" size="small" style="width: 120px;">
                <el-option label="一级类目" :value="1" />
                <el-option label="二级类目" :value="2" />
                <el-option label="三级类目" :value="3" />
              </el-select>
            </div>
          </template>
          <div ref="categoryChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 经营模式分布 -->
      <el-col :span="12">
        <el-card class="operation-mode-card">
          <template #header>
            <span>经营模式分布</span>
          </template>
          <div class="operation-mode-list">
            <div 
              v-for="mode in operationModeAnalysis" 
              :key="mode.operationMode"
              class="mode-item"
            >
              <div class="mode-header">
                <span class="mode-name">{{ mode.operationMode }}</span>
                <span class="mode-ratio">{{ formatPercentage(mode.brandRatio) }}</span>
              </div>
              <div class="mode-metrics">
                <div class="metric-row">
                  <span class="metric-label">品牌数量:</span>
                  <span class="metric-value">{{ mode.brandCount }}</span>
                </div>
                <div class="metric-row">
                  <span class="metric-label">成交金额:</span>
                  <span class="metric-value">{{ formatCurrency(mode.transactionAmount) }}万</span>
                </div>
                <div class="metric-row">
                  <span class="metric-label">平均转化率:</span>
                  <span class="metric-value">{{ formatPercentage(mode.avgConversionRate) }}</span>
                </div>
              </div>
              <div class="mode-progress">
                <el-progress 
                  :percentage="mode.amountRatio" 
                  :color="mode.color"
                  :show-text="false"
                  :stroke-width="6"
                />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 品牌表现详情弹窗 -->
    <el-dialog
      v-model="brandDetailVisible"
      title="品牌表现详情"
      width="80%"
      :before-close="handleBrandDetailClose"
      style="min-height: 600px;"
    >
      <div style="min-height: 500px; max-height: 70vh; overflow-y: auto;">
        <BrandPerformanceTable 
          :data="brandPerformanceList"
          :loading="brandTableLoading"
          :pagination="brandPagination"
          @refresh="loadBrandPerformance"
        />
      </div>
    </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, nextTick, watch, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Shop, User, Money, TrendCharts, Top, Bottom, Minus, Refresh
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { distributionApi } from '@/api/dashboard/distribution.api'
import type {
  DistributionOverviewMetrics,
  DistributionRealTimeData,
  BrandRankingData,
  OperationModeAnalysis,
  TrendDataPoint,
  BrandPerformanceData
} from '@/types/distribution'

// 动态导入组件
const BrandPerformanceTable = defineAsyncComponent(() => 
  import('./components/BrandPerformanceTable.vue')
)

// 响应式数据
const loading = ref(false)
const updateTime = ref('')
const dateRange = ref<[string, string]>(['', ''])
const trendType = ref('amount')
const categoryLevel = ref(1)
const brandDetailVisible = ref(false)
const brandTableLoading = ref(false)
const brandPagination = ref({ total: 0, pageNum: 1, pageSize: 10 })

// 图表引用
const trendChartRef = ref<HTMLDivElement>()
const categoryChartRef = ref<HTMLDivElement>()
let trendChart: echarts.ECharts | null = null
let categoryChart: echarts.ECharts | null = null

// 数据状态
const realtimeData = reactive<DistributionRealTimeData>({
  onlineBrands: 0,
  realtimeVisitors: 0,
  todayAmount: 0,
  todayOrders: 0,
  realtimeConversionRate: 0,
  lastUpdateTime: ''
})

const overviewMetrics = reactive<DistributionOverviewMetrics>({
  totalBrands: 0,
  brandGrowthRate: 0,
  activeBrands: 0,
  activeBrandRate: 0,
  totalTransactionAmount: 0,
  amountGrowthRate: 0,
  avgTransactionValue: 0,
  overallConversionRate: 0
})

const brandRanking = ref<BrandRankingData[]>([])
const operationModeAnalysis = ref<OperationModeAnalysis[]>([])
const categoryAnalysisData = ref<any[]>([])
const amountTrend = ref<TrendDataPoint[]>([])
const brandCountTrend = ref<TrendDataPoint[]>([])
const conversionTrend = ref<TrendDataPoint[]>([])
const brandPerformanceList = ref<BrandPerformanceData[]>([])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 计算属性
const currentTrendData = computed(() => {
  switch (trendType.value) {
    case 'amount':
      return amountTrend.value
    case 'brands':
      return brandCountTrend.value
    case 'conversion':
      return conversionTrend.value
    default:
      return amountTrend.value
  }
})

// 工具函数
function formatNumber(num: number): string {
  if (num == null || isNaN(num)) return '0'
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toLocaleString()
}

function formatCurrency(num: number): string {
  if (num == null || isNaN(num)) return '0.00'
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

function formatPercentage(num: number): string {
  if (num == null || isNaN(num)) return '0.00%'
  return num.toFixed(2) + '%'
}

function formatGrowthRate(rate: number): string {
  if (rate == null || isNaN(rate)) return '0.00%'
  const sign = rate >= 0 ? '+' : ''
  return sign + rate.toFixed(2) + '%'
}

function getGrowthClass(rate: number): string {
  return rate >= 0 ? 'positive' : 'negative'
}

function getTrendClass(trend: string): string {
  const classMap: Record<string, string> = {
    up: 'trend-up',
    down: 'trend-down',
    stable: 'trend-stable'
  }
  return classMap[trend] || 'trend-stable'
}

// 数据加载函数
async function loadDashboardData() {
  try {
    loading.value = true
    const params = dateRange.value.length === 2 ? {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    } : undefined

    console.log('开始加载看板数据，参数：', params)

    const [
      overviewRes,
      realtimeRes,
      rankingRes,
      operationRes,
      categoryRes,
      amountTrendRes,
      brandTrendRes,
      conversionTrendRes
    ] = await Promise.all([
      distributionApi.getOverviewMetrics(params),
      distributionApi.getRealTimeData(),
      distributionApi.getBrandRanking({ ...params, limit: 10 }),
      distributionApi.getOperationModeAnalysis(params),
      distributionApi.getCategoryAnalysis({ ...params, categoryLevel: categoryLevel.value as 1 | 2 | 3 }),
      distributionApi.getAmountTrend(params),
      distributionApi.getBrandCountTrend(params),
      distributionApi.getConversionTrend(params)
    ])

    console.log('API返回数据：', {
      overviewRes,
      realtimeRes, 
      rankingRes,
      operationRes,
      categoryRes,
      amountTrendRes,
      brandTrendRes,
      conversionTrendRes
    })

    // 安全地赋值数据
    Object.assign(overviewMetrics, overviewRes || {})
    Object.assign(realtimeData, realtimeRes || {})
    
    // 处理带有data字段的响应
    brandRanking.value = (rankingRes && rankingRes.data && Array.isArray(rankingRes.data)) ? 
                        rankingRes.data : []
    operationModeAnalysis.value = (operationRes && operationRes.data && Array.isArray(operationRes.data)) ? 
                                 operationRes.data : []
    
    // 更新类目数据 - 使用与主加载函数相同的处理逻辑
    let categoryData = []
    if (categoryRes && (categoryRes as any).data && (categoryRes as any).data.data && Array.isArray((categoryRes as any).data.data)) {
      // 处理 { data: { data: [...] } } 结构
      categoryData = (categoryRes as any).data.data
      console.log('监听函数: 使用嵌套data.data结构，数据长度:', categoryData.length)
    } else if (categoryRes && (categoryRes as any).data && Array.isArray((categoryRes as any).data)) {
      // 处理 { data: [...] } 结构
      categoryData = (categoryRes as any).data
      console.log('监听函数: 使用data结构，数据长度:', categoryData.length)
    } else if (categoryRes && Array.isArray(categoryRes)) {
      // 处理直接数组结构
      categoryData = categoryRes
      console.log('监听函数: 使用直接数组结构，数据长度:', categoryData.length)
    }
    categoryAnalysisData.value = categoryData
    console.log('监听函数: 更新后的类目数据:', categoryAnalysisData.value)
    
    amountTrend.value = (amountTrendRes && amountTrendRes.data && Array.isArray(amountTrendRes.data)) ? 
                       amountTrendRes.data : []
    brandCountTrend.value = (brandTrendRes && brandTrendRes.data && Array.isArray(brandTrendRes.data)) ? 
                           brandTrendRes.data : []
    conversionTrend.value = (conversionTrendRes && conversionTrendRes.data && Array.isArray(conversionTrendRes.data)) ? 
                           conversionTrendRes.data : []

    updateTime.value = new Date().toLocaleString()
    
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    console.error('加载看板数据失败:', error)
    ElMessage.error('加载数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

async function loadBrandPerformance(searchParams?: any) {
  try {
    brandTableLoading.value = true
    
    // 合并日期范围和搜索参数
    let params: any = {
      pageNum: brandPagination.value.pageNum,
      pageSize: brandPagination.value.pageSize
    }
    
    // 添加日期范围
    if (dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    // 添加搜索参数
    if (searchParams) {
      Object.assign(params, searchParams)
      // 如果有新的分页参数，更新本地分页状态
      if (searchParams.pageNum) {
        brandPagination.value.pageNum = searchParams.pageNum
      }
      if (searchParams.pageSize) {
        brandPagination.value.pageSize = searchParams.pageSize
      }
    }

    console.log('品牌表现查询参数:', params)
    const res = await distributionApi.getBrandPerformanceList(params)
    brandPerformanceList.value = res.list
    // 确保total是数字类型
    brandPagination.value.total = typeof res.total === 'string' ? parseInt(res.total, 10) : (res.total || 0)
    console.log('品牌表现数据加载完成:', { 
      listSize: res.list.length, 
      total: brandPagination.value.total,
      totalType: typeof brandPagination.value.total,
      pageNum: brandPagination.value.pageNum,
      pageSize: brandPagination.value.pageSize
    })
  } catch (error) {
    console.error('加载品牌表现数据失败:', error)
    ElMessage.error('加载品牌数据失败')
  } finally {
    brandTableLoading.value = false
  }
}

// 图表初始化
function initCharts() {
  initTrendChart()
  initCategoryChart()
}

function initTrendChart() {
  if (!trendChartRef.value) return
  
  if (trendChart) {
    trendChart.dispose()
  }
  
  trendChart = echarts.init(trendChartRef.value)
  
  // 确保数据是数组类型
  const trendData = currentTrendData.value || []
  if (!Array.isArray(trendData)) {
    console.warn('趋势图数据不是数组类型:', trendData)
    return
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: trendData.map(item => item.date || '')
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: getTrendSeriesName(),
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      },
      data: trendData.map(item => getTrendValue(item))
    }]
  }
  trendChart.setOption(option)
}

function initCategoryChart() {
  if (!categoryChartRef.value) return
  
  if (categoryChart) {
    categoryChart.dispose()
  }
  
  categoryChart = echarts.init(categoryChartRef.value)
  
  // 使用实际的类目分析数据，如果没有数据则显示空状态
  let chartData = []
  
  if (categoryAnalysisData.value && categoryAnalysisData.value.length > 0) {
    // 使用实际数据
    chartData = categoryAnalysisData.value.map((item, index) => ({
      value: item.transactionAmount || 0,
      name: item.categoryName || `类目${index + 1}`,
      itemStyle: {
        color: item.color || getDefaultColor(index)
      }
    }))
  } else {
    // 如果没有数据，显示加载中或无数据状态
    chartData = [
      { 
        value: 1, 
        name: '暂无数据', 
        itemStyle: { 
          color: '#e5e7eb' 
        }
      }
    ]
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params: any) {
        if (params.name === '暂无数据') {
          return '暂无数据'
        }
        return `${params.seriesName} <br/>${params.name}: ${params.value}万元 (${params.percent}%)`
      }
    },
    legend: {
      orient: 'vertical',
      right: '8%',
      top: 'center',
      textStyle: {
        fontSize: 10,
        color: '#666'
      },
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 6,
      icon: 'circle',
      // 根据数据动态显示图例
      data: chartData.map(item => item.name)
    },
    series: [{
      name: `${categoryLevel.value}级类目分布`,
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['35%', '50%'],
      data: chartData,
      emphasis: {
        itemStyle: {
          shadowBlur: 6,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.2)'
        }
      },
      label: {
        show: chartData[0].name !== '暂无数据',
        position: 'inside',
        formatter: '{d}%',
        fontSize: 9,
        color: '#fff',
        fontWeight: 'bold'
      },
      labelLine: {
        show: false
      },
      itemStyle: {
        borderWidth: 1,
        borderColor: '#fff'
      }
    }]
  }
  
  categoryChart.setOption(option, true) // 使用 true 参数强制重绘
}

// 获取默认颜色的辅助函数
function getDefaultColor(index: number): string {
  const colors = [
    '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
    '#40E0D0', '#FF69B4', '#32CD32', '#FFD700', '#FF4500'
  ]
  return colors[index % colors.length]
}

function getTrendSeriesName(): string {
  const nameMap: Record<string, string> = {
    amount: '成交金额',
    brands: '品牌数量',
    conversion: '转化率'
  }
  return nameMap[trendType.value] || '成交金额'
}

function getTrendValue(item: TrendDataPoint): number {
  switch (trendType.value) {
    case 'amount':
      return item.transactionAmount || 0
    case 'brands':
      return item.brandCount || 0
    case 'conversion':
      return item.conversionRate || 0
    default:
      return item.transactionAmount || 0
  }
}

// 事件处理
function handleDateChange() {
  loadDashboardData()
}

function refreshData() {
  loadDashboardData()
}

function showBrandDetail() {
  // 重置分页信息
  brandPagination.value = { total: 0, pageNum: 1, pageSize: 10 }
  brandDetailVisible.value = true
  loadBrandPerformance()
}

function handleBrandDetailClose() {
  brandDetailVisible.value = false
}

// 监听趋势类型变化
watch(trendType, () => {
  nextTick(() => {
    initTrendChart()
  })
})

// 监听类目级别变化
watch(categoryLevel, async () => {
  if (loading.value) return
  
  try {
    loading.value = true
    console.log('类目级别变化，重新加载数据:', categoryLevel.value)
    
    const params = dateRange.value.length === 2 ? {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      categoryLevel: categoryLevel.value as 1 | 2 | 3
    } : { categoryLevel: categoryLevel.value as 1 | 2 | 3 }

    const categoryRes = await distributionApi.getCategoryAnalysis(params)
    console.log('类目数据返回结果:', categoryRes)
    
    // 更新类目数据 - 使用与主加载函数相同的处理逻辑
    let categoryData = []
    if (categoryRes && (categoryRes as any).data && (categoryRes as any).data.data && Array.isArray((categoryRes as any).data.data)) {
      // 处理 { data: { data: [...] } } 结构
      categoryData = (categoryRes as any).data.data
    } else if (categoryRes && (categoryRes as any).data && Array.isArray((categoryRes as any).data)) {
      // 处理 { data: [...] } 结构
      categoryData = (categoryRes as any).data
    } else if (categoryRes && Array.isArray(categoryRes)) {
      // 处理直接数组结构
      categoryData = categoryRes
    }
    categoryAnalysisData.value = categoryData
    
    // 重新初始化图表
    nextTick(() => {
      initCategoryChart()
    })
  } catch (error) {
    console.error('加载类目数据失败:', error)
    ElMessage.error('加载类目数据失败')
    // 设置空数据以显示无数据状态
    categoryAnalysisData.value = []
    nextTick(() => {
      initCategoryChart()
    })
  } finally {
    loading.value = false
  }
})

// 组件挂载
onMounted(() => {
  // 设置默认日期范围（最近30天）
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]
  
  loadDashboardData()
})

onUnmounted(() => {
  if (trendChart) {
    trendChart.dispose()
  }
  if (categoryChart) {
    categoryChart.dispose()
  }
})
</script>

<style scoped lang="scss">
.distribution-dashboard {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;

  // 页面头部
  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .header-left {
      .dashboard-title {
        display: flex;
        align-items: center;
        font-size: 22px;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 6px 0;

        .title-icon {
          margin-right: 10px;
          font-size: 24px;
          color: #409eff;
        }
      }

      .update-time {
        font-size: 13px;
        color: #6b7280;
      }
    }

    .header-controls {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }

  // 实时指标卡片
  .realtime-metrics {
    margin-bottom: 16px;

    .metric-card {
      position: relative;
      display: flex;
      align-items: center;
      padding: 18px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
      }

      .metric-icon {
        width: 48px;
        height: 48px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 14px;

        .el-icon {
          font-size: 20px;
          color: white;
        }
      }

      .metric-content {
        flex: 1;

        .metric-value {
          font-size: 24px;
          font-weight: 700;
          color: #1f2937;
          margin-bottom: 2px;
        }

        .metric-label {
          font-size: 13px;
          color: #6b7280;
          margin-bottom: 6px;
        }

        .metric-status {
          font-size: 11px;
          padding: 2px 6px;
          border-radius: 10px;
          font-weight: 500;

          &.online {
            background: #dcfce7;
            color: #16a34a;
          }

          &.positive {
            background: #dcfce7;
            color: #16a34a;
          }
        }
      }

      // 不同卡片的主题色
      &.online-brands::before {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.realtime-visitors::before {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.today-amount::before {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &.conversion-rate::before {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }
  }

  // 概览指标
  .overview-section {
    margin-bottom: 16px;

    .overview-card {
      padding: 18px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
      }

      .card-content {
        .card-value {
          font-size: 28px;
          font-weight: 700;
          color: #1f2937;
          margin-bottom: 6px;
        }

        .card-label {
          font-size: 13px;
          color: #6b7280;
          margin-bottom: 8px;
        }

        .card-growth {
          display: flex;
          align-items: center;
          font-size: 13px;
          font-weight: 600;

          &.positive {
            color: #16a34a;
          }

          &.negative {
            color: #dc2626;
          }

          .el-icon {
            margin-right: 3px;
          }
        }

        .card-sub {
          font-size: 11px;
          color: #9ca3af;
        }
      }
    }
  }

  // 主要分析区域
  .main-analysis {
    margin-bottom: 16px;

    .el-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      :deep(.el-card__header) {
        padding: 16px 20px;
        border-bottom: 1px solid #f1f5f9;

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: 600;
          color: #1f2937;
          font-size: 15px;
        }
      }

      :deep(.el-card__body) {
        padding: 16px 20px;
      }
    }

    .chart-container {
      width: 100%;
    }

    // 排行榜样式
    .ranking-list {
      height: 290px;
      overflow-y: auto;
      padding: 0 4px 0 0;
      margin: 0;

      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 2px;
      }

      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 2px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
      }

      .ranking-item {
        display: flex;
        align-items: center;
        padding: 8px 4px;
        border-bottom: 1px solid #f1f5f9;
        transition: all 0.3s ease;
        min-height: 40px;
        box-sizing: border-box;

        &:hover {
          background: #f8fafc;
          border-radius: 4px;
          border-bottom-color: transparent;
        }

        &:last-child {
          border-bottom: none;
        }

        .rank-number {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
          margin-right: 8px;
          background: #f1f5f9;
          color: #6b7280;
          font-size: 11px;
          flex-shrink: 0;
        }

        &.rank-1 .rank-number {
          background: linear-gradient(135deg, #ffd700, #ffed4e);
          color: #92400e;
          box-shadow: 0 2px 6px rgba(255, 215, 0, 0.3);
        }

        &.rank-2 .rank-number {
          background: linear-gradient(135deg, #c0c0c0, #e5e7eb);
          color: #374151;
          box-shadow: 0 2px 6px rgba(192, 192, 192, 0.3);
        }

        &.rank-3 .rank-number {
          background: linear-gradient(135deg, #cd7f32, #d97706);
          color: #451a03;
          box-shadow: 0 2px 6px rgba(205, 127, 50, 0.3);
        }

        .brand-info {
          flex: 1;
          min-width: 0;
          overflow: hidden;

          .brand-name {
            font-size: 12px;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.2;
          }

          .brand-category {
            font-size: 9px;
            color: #6b7280;
            background: #f3f4f6;
            padding: 1px 4px;
            border-radius: 6px;
            display: inline-block;
            white-space: nowrap;
            line-height: 1.1;
          }
        }

        .brand-metrics {
          text-align: right;
          flex-shrink: 0;
          width: 70px;

          .metric-amount {
            font-size: 12px;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 2px;
            line-height: 1.2;
          }

          .metric-trend {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            font-size: 9px;
            font-weight: 600;
            line-height: 1.1;

            .el-icon {
              margin-right: 1px;
              font-size: 9px;
            }

            &.trend-up {
              color: #16a34a;
            }

            &.trend-down {
              color: #dc2626;
            }

            &.trend-stable {
              color: #6b7280;
            }
          }
        }
      }
    }
  }

  // 分布分析
  .distribution-analysis {
    .el-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      border: 1px solid #f1f5f9;

      :deep(.el-card__header) {
        padding: 10px 16px;
        border-bottom: 1px solid #f1f5f9;
        background: #fafbfc;

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: 600;
          color: #1f2937;
          font-size: 14px;
        }
      }

      :deep(.el-card__body) {
        padding: 10px 16px;
      }
    }

    .chart-container {
      height: 240px !important;
    }

    .operation-mode-list {
      height: 240px;
      overflow-y: auto;
      padding-right: 4px;

      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 2px;
      }

      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 2px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
      }

      .mode-item {
        padding: 10px;
        border: 1px solid #f1f5f9;
        border-radius: 6px;
        margin-bottom: 6px;
        transition: all 0.3s ease;
        background: #fff;

        &:hover {
          border-color: #409eff;
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
          transform: translateY(-1px);
        }

        &:last-child {
          margin-bottom: 0;
        }

        .mode-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 6px;

          .mode-name {
            font-size: 13px;
            font-weight: 600;
            color: #1f2937;
          }

          .mode-ratio {
            font-size: 11px;
            font-weight: 700;
            color: #409eff;
            background: #e8f4ff;
            padding: 2px 6px;
            border-radius: 8px;
          }
        }

        .mode-metrics {
          margin-bottom: 6px;

          .metric-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2px;

            &:last-child {
              margin-bottom: 0;
            }

            .metric-label {
              font-size: 11px;
              color: #6b7280;
            }

            .metric-value {
              font-size: 11px;
              font-weight: 600;
              color: #1f2937;
            }
          }
        }

        .mode-progress {
          :deep(.el-progress-bar__outer) {
            border-radius: 6px;
            height: 4px;
            background-color: #f1f5f9;
          }

          :deep(.el-progress-bar__inner) {
            border-radius: 6px;
          }
        }
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    padding: 12px;

    .dashboard-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;

      .header-controls {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .realtime-metrics,
    .overview-section {
      :deep(.el-col) {
        margin-bottom: 12px;
      }
    }

    .main-analysis {
      :deep(.el-col) {
        margin-bottom: 16px;
      }
    }
  }
}

// 全局趋势图标样式
.trend-up {
  color: #16a34a !important;
}

.trend-down {
  color: #dc2626 !important;
}

.trend-stable {
  color: #6b7280 !important;
}
</style>